<?php

namespace login\model;

class AddUserDAL {

	/**
	 * @var \mysqli
	 */
	private $mysqli;

	function __construct(\mysqli $mysqli) {
		$this->mysqli = $mysqli;
	}

	/**
	 * @param string $username
	 * @param string $password
	 * @throws \Exception
	 */
	public function addNewUser($username, $password, $repeatPassword) {

		try {
			$this->checkUserCreds($username, $password, $repeatPassword);
		} catch (\Exception $e) {
			throw new \Exception($e->getMessage());
		}

		
		$sqlQ = "INSERT INTO `Users` (UserName, PW) VALUES (?, ?)";

		$stmt = $this->mysqli->prepare($sqlQ);
		if($stmt == false) {
			throw new \Exception("Prepare of sql question failed " . $this->mysqli->error);
		}

		$res = $stmt->bind_param("ss", $username, $password);
		if ($res == false) {
			throw new \Exception("Bind param failed " . $stmt->error);
		}

		$res = $stmt->execute();
		if($res == false) {
			throw new \Exception("Database execute failed " . $stmt->error);
		}
	}

	public function checkUserCreds($username, $password, $repeatPassword) {
		if ($this->findUser($username) == true) {
			throw new \Exception("Användarnamn upptaget.");
		}
		if(strlen($username) < 3) {
			throw new \Exception("Användarnamner har för få tecken. Minst 3 tecken.");
		}
		if(strlen($password) < 6) {
			throw new \Exception("Lösenordet har för få tecken. Minst 6 tecken.");
		}
		if($repeatPassword != $password) {
			throw new \Exception("Lösenorden matchar inte.");
		}
		if($username != strip_tags($username)){
			throw new \Exception("Ogiltigt användarnamn.");
		}
	}

	public function findUser($username) {
		$loginDAL = new LoginDal($this->mysqli);

		try {
			$loginDAL->getUser($username);
			return true;
		} catch (\Exception $e) {
			return false;
		}
	}
}